jQuery.validator.addMethod("checkBalance", function(value,element) {
    var  balance=0;
    return this.optional(element) || value>balance;
}, $.validator.format("数值必须大于0"));
//必输字段 面额
$("#amount").blur(function(){
    if(this.value != 0 ){
        $("#message").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//必输字段 主题名称
$("#topicName").blur(function(){
    if(this.value != 0 ){
        $("#message0").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//必输字段 数量
$("#totalCount").blur(function(){
    if(this.value != 0 ){
        $("#message2").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//spu sku 文本框校验
function testShuRu(a)
{
    var patt1=new RegExp("^[;.a-zA-Z0-9\u0020]*$");
    if(!patt1.test(a)){
        $.Huimodalalert('请按商品编码组成规则：输入字母、数字、英文状态下分号、点',2000);
        // $("#spuText").val().replace(/[^;.a-zA-Z0-9]/g, "");
    }
}

function getTopicType() {
    if($("#topicType").val()==20){
        $("#orderMoney").html("单笔订单运费金额满");
        $("#applRange").hide();
        $("#applCate").hide();
        $("#cateLevel").hide();
        $("#tab_goods").hide();
    }else{
        $("#orderMoney").html("单笔订单适用商品金额满");
        $("#applRange").show();
        $("#applCate").show();
        $("#cateLevel").show();
        $("#tab_goods").show();
    }
}

var applPaidType ='';
$("input[name='paidType']").change(function() {
    applPaidType ='';
    var groupCheckbox =  $("input[name='paidType']");
    for(var i=0;i<groupCheckbox.length;i++){
        if(groupCheckbox[i].checked){
            var val =groupCheckbox[i].value;
            if(i==groupCheckbox.length-1){
                applPaidType += val ;
            }else{
                applPaidType += val +',';
            }
        }
        if(groupCheckbox[i].checked==false){
            document.getElementById("applPaidType0").checked = false;
        }
    }
    console.log(applPaidType);

});


var count = 0;//默认 没有
function check_pay(){
    if(count==0){
        document.getElementById("applPaidType0").checked=true;
        $("input[name='paidType']").prop("checked",true);
        count = 1;
        applPaidType = document.getElementById("applPaidType0").value;
        console.log(applPaidType);
    }else if(count==1){
        document.getElementById("applPaidType0").checked=false;
        $("input[name='paidType']").prop("checked",false);
        count = 0;
        applPaidType = '';
    }
}

var checkLength = function(dom, maxLength){
    var l = 0;
    for(var i=0; i<dom.value.length; i++) {
        if (/[\u4e00-\u9fa5]/.test(dom.value[i])) {
            l+=2;
        } else {
            l++;
        }
        if (l > maxLength) {
            dom.value = dom.value.substr(0,i);
            break;
        }
    }
};


function putDataToPage() {
    /*渲染spu sku值到页面*/
    var formData = new FormData();
    formData.append("topicId", 100);
    formData.append("applProduct", 1);
    if($("#tabbox1")[0].style.display == "block"){
        formData.append('type',1);
    }
    else if($("#tabbox2")[0].style.display == "block"){
        formData.append('type',2);
    }
    formData.append('spulist',$('#spuText').val());
    formData.append('skulist',$('#skuText').val());
    formData.append('spulist1',$('#spuText1').val());
    formData.append('skulist1',$('#skuText1').val());
    formData.append('file', $("#fileUp")[0].files[0]);
    // console.log($("#fileUp")[0].value)
    $.ajax({
        url: root.couponInter.coupon_excelImportProduct,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            if(data.code==1){
                $.Huimodalalert(data.message,2000);
            }
            var spuStr = "";
            var skuStr = "";
            var oldSpuStr = $("#spuText").val();
            var oldSkuStr = $('#skuText').val();
            var oldSpuStr1 = $("#spuText1").val();
            var oldSkuStr1 = $('#skuText1').val();
            for (var i = 0; i < data.successList.length; i++) {
                if (i < data.successList.length - 1) {
                    if (data.successList[i].spuCode!=null){
                        spuStr = data.successList[i].spuCode+ "  ;  "+spuStr;
                    }
                    if (data.successList[i].skuCode!=null){
                        skuStr = data.successList[i].skuCode + "  ;  "+skuStr;
                    }
                }
                else if (i == data.successList.length - 1) {
                    if (data.successList[i].spuCode!=null){
                        spuStr += data.successList[i].spuCode;
                    }
                    if (data.successList[i].skuCode!=null){
                        skuStr += data.successList[i].skuCode;
                    }
                }
            }

            // if (skuStr.lastIndexOf(";")==(skuStr.length-1)){
            //     $("#skuText").val(skuStr.substring(0,skuStr.length-1));
            // }
            if($("#tabbox1")[0].style.display == "block"){
                if($("#spuText").val()==''){
                    $("#spuText").val(spuStr);
                }
                else{
                    if(spuStr!=''){
                        $("#spuText").val(oldSpuStr+';'+spuStr);
                    }
                }
                if($("#skuText").val()==''){
                    $("#skuText").val(skuStr);
                }
                else{
                    if(skuStr!=''){
                        console.log('oldSkuStr'+':'+oldSkuStr);
                        $("#skuText").val(oldSkuStr+';'+skuStr);
                    }
                }
            }
            else if($("#tabbox2")[0].style.display == "block"){
                if($("#spuText1").val()==''){
                    $("#spuText1").val(spuStr);
                }
                else{
                    if(spuStr!=''){
                        $("#spuText1").val(oldSpuStr+';'+spuStr);
                    }
                }
                if($("#skuText1").val()==''){
                    $("#skuText1").val(skuStr);
                }
                else{
                    if(skuStr!=''){
                        console.log('oldSkuStr'+':'+oldSkuStr);
                        $("#skuText1").val(oldSkuStr+';'+skuStr);
                    }
                }
            }
            $("#fileUp")[0].value = ""

            var p=[];
            var k=[];
            var u=[];
            var o=[];
            var failSpu=[];
            var failSku=[];
            for(var i=0;i<data.successList.length;i++){
                var j=i+1;
                if(data.successList[i].spuCode==null){
                    p.push(j);
                }
                if(data.successList[i].skuCode==null){
                    k.push(j);
                }
                if(data.successList[i].spuCode!=null){
                    u.push(j);
                }
                if(data.successList[i].skuCode!=null){
                    o.push(j);
                }
            };

            var q=u.length+o.length;
            if(data.failSpuId.length == 0 && data.failSkuId.length == 0){
				if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                if(data.successList.length == 0){
                    $.Huimodalalert('导入的表中没有商品数据,请检查数据表!',2000);
                }else{
                    $.Huimodalalert('成功导入全部商品',2000);
                }
            }
            else if(data.failSpuId.length != 0 && data.failSkuId.length != 0){
                console.log(123)
                for(var i=0;i<data.failSpuId.length;i++){
                    failSpu.push(data.failSpuId[i]);
                };
                for(var i=0;i<data.failSkuId.length;i++){
                    failSku.push(data.failSkuId[i]);
                };
				if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSpu+'}行SPU编码和第{'+failSku+'}行SKU编码的商品:不存在!',3000);
            }
            else if(data.failSpuId.length != 0 && data.failSkuId.length == 0){
                console.log(456)
                for(var i=0;i<data.failSpuId.length;i++){
                    failSpu.push(data.failSpuId[i]);
                };
				if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSpu+'}行SPU编码的商品:不存在!',3000);
            }
            else if(data.failSpuId.length == 0 && data.failSkuId.length != 0){
                console.log(789)
                for(var i=0;i<data.failSkuId.length;i++){
                    failSku.push(data.failSkuId[i]);
                };
				if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSku+'}行SKU编码的商品:不存在!',3000);
            }
        }
    });
}

function downloadTem() {
    $.ajax({
        url: "http://192.168.7.100:8087/downloadProductExcelTemplate",
        cache: false,  //禁用缓存
        type: "GET",
        data: "",
        success: function (data) {
            console.log(data);
        }
    });
}

function upLoadFile() {
    $("#fileUp").trigger('click');
}
function getNum(Val){
    console.log(Val);

}
/*$(document).bind("click",function(e){
   console.log(e.target)
})*/
/*分类设置--------------------------------------------------------------------------------------------------------------*/
var map1={};
var map2={};
var map3=[];
var firstLevel = [];
var secondLevel = [];
var thirdLevel = [];
var secondLevelSelect = [];
var first = [];
var second = [];
var third = [];
var thirdVal = [];
var selectall = 1;
var thirdToFirst=[];

//全选
$("#selectAll").click(function(){
    /*var Ids = 0;
    first = [];
    if(selectall%2==1){
        $("input[name='classification01']").each(function(){
            $(this).prop("checked",true);
            Ids=parseInt(this.id);
            first.push(Ids);
            map1[this.id]={};
        });
        $("#classDiv2").css({
            display: "none"
        });
        $(".removeEl2").remove();
        $("#classDiv3").css({
            display: "none"
        });
        selectall++;
    }
    else{
        $("input[name='classification01']").each(function(){
            $(this).prop("checked",false);
        });
        $("input[name='classification02']").each(function(){
            $(this).prop("checked",false);
        });
        $("input[name='classification03']").each(function(){
            $(this).prop("checked",false);
        });
        selectall++;
        firstLevel=[];
        secondLevel=[];
        thirdLevel=[];
        map1={};
    }*/
    secondCategoryData = {};
    thirdCategoryData = {};
    fourthCategoryData = {};
    categoryParams1 = [];
    categoryParams2 = [];
    categoryParams3 = [];
    categoryParams4 = [];
    let categoryLevelArr = [2, 3, 4];
    categoryLevelArr.forEach((item) => {
        $("#classDiv" + item).hide();
    });
    $(".category_checked").prop("checked", true);
    for (const key in firstCategoryData) {
        firstCategoryData[key][0].checkedVal = true;
        firstCategoryData[key][0].selectAll = true;
    }
});

//重置
$('#selectReset').click(function () {
    firstCategoryData = {};
    secondCategoryData = {};
    thirdCategoryData = {};
    fourthCategoryData = {};
    categoryParams1 = [];
    categoryParams2 = [];
    categoryParams3 = [];
    categoryParams4 = [];
    let categoryLevelArr = [2, 3, 4];
    categoryLevelArr.forEach((item) => {
        $("#classDiv" + item).hide();
    });
    $(".category_checked").prop("checked", false);
    $("input[name='applRange']").each(function(){
        $(this).prop("checked",false);
    });
    /*secondLevelSelect = [];
    second = [];
    third = [];
    thirdVal = [];
    oldparentId = [];
    c=[];
    oldparentid = 0;
    $("#classDiv2").css({
        display: "none"
    });
    $(".removeEl2").remove();
    $("#classDiv3").css({
        display: "none"
    });
    $(".removeEl3").remove();
    $("input[name='classification01']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='classification02']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='classification03']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='applRange']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='applCate']").each(function(){
        $(this).prop("checked",false);
    });*/
});
/*function makeMap(){
    firstLevel = [];
    for(key1 in map1){
        thirdToFirst=[];
        var lll=0;
        for(var i in map1[key1]){
            lll++
        }
        if(lll==0){
            firstLevel.push(key1);
        }
        for(key2 in map1[key1]){
            cateThird(key1,key2);
            cateSecond(key1,key2);
        }
        // console.log(map1);
        // console.log({"1":firstLevel, "2":secondLevel, "3":thirdLevel})

    }
    console.log({"1":firstLevel, "2":secondLevel, "3":thirdLevel})
    /!*for(var i=0;i< firstLevel.length;i++){
        firstLevel[i]=parseInt(firstLevel[i])
    }*!/
}
// 判断一级二级关系
function cateSecond(key1,key2){
    $.ajax({
        url: root.goodsInter.goods_subCategory,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        async:false,
        // contentType: "application/json",
        data: {
            category_id: key1,
        },
        success: function (data) {
            var length=0;
            for(var i in map1[key1]){
                length++
            }
            if(length==data.data.length) {
                if(thirdToFirst.length==0&&$.inArray(key1,firstLevel)==-1){
                    firstLevel.push(key1);
                }
                else if(thirdToFirst.length!=0){
                    if($.inArray(key2,secondLevel)==-1){
                    }
                }
            }
            else if(length==0){
                firstLevel.push(key1);
            }
            else {
                if ($.inArray(key2, secondLevel) == -1) {
                    secondLevel.push(key2);
                }
            }
            //判断二级三级关系
            $.ajax({
                url: root.goodsInter.goods_subCategory,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                async:false,
                // contentType: "application/json",
                data: {
                    category_id: key2,
                },
                success: function (data) {
                    if(data.data.length!=map1[key1][key2].length&&map1[key1][key2].length!=0)
                    {
                        secondLevel.remove(key2);
                    }
                },
                error: function () {
                    console.log('失败')
                }
            })
        },
        error: function () {
            console.log('失败')
        }
    })
}


// 判断一级三级关系
function cateThird(key1,key2){
    $.ajax({
        url: root.goodsInter.goods_subCategory,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        async:false,
        // contentType: "application/json",
        data: {
            category_id: key2,
        },
        success: function (data) {
            if(map1[key1][key2].length!=0&&map1[key1][key2].length!=data.data.length)
            {
                thirdToFirst=thirdToFirst.concat(map1[key1][key2]);
                for(var i=0;i<map1[key1][key2].length;i++){
                    if($.inArray(map1[key1][key2][i],thirdLevel==-1)){
                        thirdLevel.push(map1[key1][key2][i])
                    }
                }
            }
        },
        error: function () {
            console.log('失败')
        }
    })
}


//数组删除某个元素
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
//字符串以什么结尾
String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d);
};


var firstlength=0;
function goods_listCategory1(classNum) {
    var user_data = {
        category_level: classNum
    }
    var succCallBack = function (data, status, response) {
        firstlength=data.data.length;
        if (data.data.length == 0) {
            $("#classSet1").append('<li class="clearfix pl-10 mb-5">无数据</li>');
        }
        else {
            for (var i = 0; i < data.data.length; i++) {
                $("#classSet1").append('<li class="clearfix pl-10 mb-5"><div class="f-l pd-5">' +
                    '<input id="' + data.data[i].category_id + '" onclick="nextbox1(this,'+data.data[i].category_code+')" name="classification01" type="checkbox" value="' + data.data[i].category_id + '" class="checkbox" />' +
                    '<label class="pl-10"  onclick="goods_listCategory2(2,' +data.data[i].category_id + ',this)">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div>' +
                    '<div class="f-r"><a onclick="firstClassAdd(\'#firstClassInp2\',2,1,' + data.data[i].category_id + ',' + data.data[i].category_code + ')" ></a>' +
                    '<a href="##" onclick="eidtInpShow(\'#firstClassInp1\',\'#addLabel1\',' + data.data[i].category_code + ',\'.firstClassId1\',\'' + data.data[i].category_name + '\',' + data.data[i].category_id + ')" "></a>' +
                    '<a href="##" onclick="deleteGoodsClass(' + data.data[i].category_id + ')"></a></div></li>')
            }
        }
    };
    return web.doAjax(root.goodsInter.goods_listCategory, 'post', user_data, succCallBack);
}
function nextbox1(that,valCode) {
    var Val = parseInt(that.value);
    if(that.checked){
        map1[Val]={};
    }
    else{
        $("#classDiv2").css({
            display: "none"
        });
        $("#classDiv3").css({
            display: "none"
        });
        delete map1[Val];
    }
    goods_listCategory2(2,Val,that.nextElementSibling)//渲染二级类
}

var oldparentId=0;
function goods_listCategory2(classNum, parentId, e) {
    if(e.previousElementSibling.checked){
        var checkbox = e.previousElementSibling;
        oldparentId=parentId;
        $(".removeEl2").remove();
        $("#classDiv2").css({
            display: "block"
        });
        $("#classDiv3").css({
            display: "none"
        });
        var user_data = {
            category_id: parentId
        }
        var succCallBack = function (data, status, response) {
            if (data.data.length == 0) {
                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5">无数据</li>');
            }
            else {
                for (var i = 0; i < data.data.length; i++) {
                    var categoryId = data.data[i].category_id;
                    if(checkbox.checked){
                        if($.inArray(categoryId,second)!=-1){
                            $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5"><input onclick="nextbox2(this,'+data.data[i].category_code+','+parentId+')"  name="classification02" type="checkbox" value="' + data.data[i].category_id + '"  class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.data[i].category_id + ','+parentId+',this)">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                        }
                        else {
                            $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox2(this,'+data.data[i].category_code+','+parentId+')" name="classification02" type="checkbox" value="' + data.data[i].category_id + '" checked="checked" class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.data[i].category_id + ','+parentId+',this)" >' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                        }
                        $("input[name='classification02']").each(function(){
                            if(this.checked){
                                map2[this.value]=[];
                            }
                        });
                        map1[parentId]=map2;
                        map2={};
                    }
                    else{
                        $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5"><input onclick="nextbox2(this,'+data.data[i].category_code+','+parentId+')"  name="classification02" type="checkbox" value="' + data.data[i].category_id + '"  class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.data[i].category_id + ','+parentId+',this)">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                    }
                }
            }
        };
        return web.doAjax(root.goodsInter.goods_subCategory, 'post', user_data, succCallBack);
    }
}


var oldparentIds = [];
function nextbox2(that,valCode,parentId) {
    var a=0;
    var b=[];
    var Val = parseInt(that.value)
    /!* if($.inArray(parentId,oldparentIds)==-1){
         map2 = new Map();
     }*!/
    if(that.checked){
        second.remove(Val)
        map1[parentId][Val]=[];
        $("input[name='classification02']").each(function(){
            if(this.checked){
                a++
            }
        });
        var levelsecond = document.getElementsByName('classification02').length;
    }
    else{
        second.push(Val)
        delete map1[parentId][Val];
        $("#classDiv3").css({
            display: "none"
        });
        $("input[name='classification02']").each(function(){
            if(this.checked){
                b.push(parseInt(this.value));
            }
        });
        b=[];
    }
}
function goods_listCategory3(classNum, parentId, grandParentId, e) {
    var checkbox = e.previousElementSibling;

    if(checkbox.checked) {
        $("#classDiv3").css({
            display: "block"
        });
        $(".removeEl3").remove();
        var user_data = {
            category_id: parentId
        }
        var succCallBack = function (data, status, response) {
            if (data.data.length == 0) {
                $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5">无数据</li>');
            }
            else {
                for (var i = 0; i < data.data.length; i++) {
                    var categoryId = data.data[i].category_id.toString()
                    if (checkbox.checked) {
                        if ($.inArray(categoryId, third) != -1) {
                            $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.data[i].category_code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.data[i].category_id + '"  class="" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.data[i].category_id + ',' + grandParentId + ')">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                        }
                        else {
                            $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.data[i].category_code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.data[i].category_id + '" checked="checked" class="checkbox" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.data[i].category_id + ',' + grandParentId + ')">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                        }
                    }
                    else {
                        $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.data[i].category_code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.data[i].category_id + '"  class="" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.data[i].category_id + ',' + grandParentId + ')">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                    }
                }
                $("input[name='classification03']").each(function () {
                    if (this.checked) {
                        map3.push(this.value);
                    }
                });
                map1[grandParentId][parentId] = map3;
                map3 = [];
            }
        }
        return web.doAjax(root.goodsInter.goods_subCategory, 'post', user_data, succCallBack);
    }
}

function nextbox3(that,valCode, parentId, grandParentId) {
    var c=[]
    var thirds = 0;
    var seconds = 0;
    if(that.checked){
        $("input[name='classification03']").each(function(){
            if(this.checked){
                map3.push(this.value);
                thirds++;
            }
        });
        $("input[name='classification02']").each(function(){
            if(this.checked){
                seconds++;
            }
        });
        var levelthird = document.getElementsByName('classification03').length;
        var levelsecond = document.getElementsByName('classification02').length;

        var k=0;
        for(key in map1[grandParentId][parentId]){
            k++
        }
        map1[grandParentId][parentId]=map3;
        if(seconds==k){
            map1[grandParentId][parentId]=[];
        }
        map3=[];
        third.remove(that.value);
    }
    else{
        third.push(that.value)
        $("input[name='classification03']").each(function(){
            if(this.checked){
                map3.push(this.value);
                c.push(parseInt(this.value))
            }
        });
        c=[];
        map1[grandParentId][parentId]=map3;
        map3=[];
        /!*thirdLevel.remove(that.value)*!/
    }
    var thirdArray=[];
    /!*$.ajax({
        url: root.goodsInter.goods_subCategory,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        // contentType: "application/json",
        data: {
            category_id: parentId,
        },
        success: function (data) {
            console.log(data.data);
            var thirdSelect = [];
            var a = document.getElementById('classSet3');
            var b=a.getElementsByTagName('input');
            for(var i = 0; i < b.length; i++){
                if(b[i].checked)
                    thirdSelect.push(b[i].value);
            }
            console.log(thirdSelect);
            if(thirdSelect.length==data.data.length){
                for(var i in thirdSelect){
                   thirdLevel.remove(thirdSelect[i]);
                }
                if($.inArray(parentId,secondLevel)==-1){
                    secondLevel.push(parentId);
                }
            }
            else{
                for(var i in thirdSelect){
                    if($.inArray(thirdSelect[i],thirdLevel)==-1){
                        thirdLevel.push(thirdSelect[i]);
                    }
                }
                if($.inArray(parentId,secondLevel)!=-1){
                    secondLevel.remove(parentId);
                }
            }
            console.log(firstLevel)
            console.log(secondLevel)
            console.log(thirdLevel)
        },
        error: function () {
            console.log('失败')
        }
    })*!/

}*/

//提交
var range = 0;
$("#coupon-add").validate({
    rules: {
        couponName: {
            required: true
        },
        amount:{
            required: true,
            checkBalance:true,
        },
        totalCount:{
            required: true,
            checkBalance:true,
        },
        demoradio1:{
            required: true
        },
        demoradio2:{
            required:true
        },
        applPort:{
            required:true
        },
        applCategoryIntroduce:{
            required:true
        },
        applCate:{
            // required:true
          required:function () {
                if($('input:radio[name="applRange"]:checked').val()==0 || $('input:radio[name="applRange"]:checked').val()==1 || $('input:radio[name="applRange"]:checked').val()==2 ){
                    return true;
                }
                else{
                    return false;
                }
            }
        },
        useCondition:{
            required:function () {
                if($('input:radio[name="demoradio1"]:checked').val()==2){
                    return true;
                }
                else{
                    return false;
                }
            },
            min:1,
        },
        dayNumber:{
            required:function () {
                if($('input:radio[name="demoradio2"]:checked').val()==2){
                    return true;
                }
                else{
                    return false;
                }
            }
        },
        logmin:{
            required:function () {
                if($('input:radio[name="demoradio2"]:checked').val()==1){
                    return true;
                }
                else{
                    return false;
                }
            }
        },
        applCategoryIntroduce:{
            required:function () {
                if($('#applCategoryIntroduce').val()!=''){
                    return true;
                }
                else{
                    return false;
                }
            }
        },
        automatic:{
            required:true
        },
    },
    messages:{
        demoradio1:{
            required:"请选择"
        },
        demoradio2:{
            required:"请选择"
        },
        applPort:{
            required:"请选择"
        },
        // applRange:{
        //     required:"请选择"
        // },
        applCate:{
            required:"请选择"
        },
        dayNumber: {
            required: ""
        },
        useCondition: {
            required: ""
        },
        logmin:{
            required:""
        },
        automatic:{
            required:"请选择"
        },

    },
    errorPlacement: function (error, element) {//指定错误信息位置
        if (element.is(':radio') || element.is(':checkbox')) { //如果是radio或checkbox
            var eid = element.attr('name'); //获取元素的name属性
            error.appendTo(element.parent().prev()); //将错误信息添加当前元素的父结点后面
        } else {
            error.insertAfter(element);
        }
    },
    onkeyup: false,
    focusCleanup: false,
    success:function(){
        $('.tip').hide()
    },
    submitHandler:function(){
        makeMap();
        $("#bottm").attr("disabled", true);
        //选中 指定品类
        if($("input:radio[name='applRange']:checked").val()!=undefined){
            range=$("input[name='applRange']:checked").val();
            //是 全选=>全场通用
            if(JSON.stringify(firstCategoryData).indexOf("false") == -1){
                range=0;
            }
        }else{
            if($("#topicType").val()==20){//运费券
                range=0;
            }else{
                range=3;
            }
        }
        var condition=$('input:radio[name="demoradio1"]:checked').val();
        var date=$('input:radio[name="demoradio2"]:checked').val();
        var dayNumber='';
        var useBegtime='';
        var useEndtime='';
        var useCondition=0;
        if(date==1){
            useBegtime=$("#logmin").val();
            useEndtime=$("#logmax").val();
            dayNumber = "";
        }
        else if(date==2){
            dayNumber = $("input[name=dayNumber]:text").val();
            useBegtime='';
            useEndtime='';
        }
        if(condition==1){
            useCondition=0;
        }
        else if(condition==2){
            useCondition=$('#useCondition').val();
        }
        if($("#topicType").val()==20){//运费券
            $("#applRange").val("0");
            $("#applCate").val("0");
            firstlength=0;
            $('#spuText').val("");
            $('#skuText').val("");
            $('#spuText1').val("");
            $('#skuText1').val("");
        }
        applPaidType = '';
        if(document.getElementById("applPaidType0").checked){
            applPaidType = $('#applPaidType0').val();
        }else{
            var groupCheckbox =  $("input[name='paidType']");
            for(i=0;i<groupCheckbox.length;i++){
                if(groupCheckbox[i].checked){
                    var val =groupCheckbox[i].value;
                    if(i==groupCheckbox.length-1){
                        applPaidType += val ;
                    }else{
                        applPaidType += val +',';
                    }
                }
            }
        }
        console.log(applPaidType);
        console.log("range: "+range);
        console.log("cate: "+$("input[name=applCate]:checked").val());
        $.ajax({
            contentType:'application/json',
            url: root.couponInter.coupon_createTopic,
            cache: false,  //禁用缓存
            type: "POST",
            data: JSON.stringify({
                "couponTopic":{
                    "topicScope":20,
                    "purpose":10,
                    "topicType":$("#topicType").val(),
                    "createUsername":$("#createUsername").html(),
                    "createDept":$("#createDept").html(),
                    "grantType":$("#grantType").val(),
                    "topicName":$("#topicName").val(),
                    "shopId":$("#shopId").val(),
                    "totalCount":$("#totalCount").val(),
                    "amount":$("#amount").val(),
                    "useCondition":useCondition,
                    "useBegtime":useBegtime,
                    "useEndtime":useEndtime,
                    "dayNumber":dayNumber,
                    "description":$("#description").val(),
                    "introduction":$("#introduction").val(),
                    "reason":$("#reason").val(),
                    "applPort":$("input[name=applPort]:checked").val(),
                    "applRange":range,
                    "applCate":$("input[name=applCate]:checked").val(),
                    "applPaidType":applPaidType,
                    "applCategoryIntroduce":$("#applCategoryIntroduce").val(),
                    "topicUrl":$("#topicUrl").val(),
                    "topicUseTag":$("input[name=automatic]:checked").val(),
                    "priceType":$("input[name=priceType]:checked").val()
                },
                "cateIds":{
                    "1":categoryParams1,
                    "2":categoryParams2,
                    "3":categoryParams3,
                    "4":categoryParams4,
                },
                "spuSkuStr":{
                    "1":{
                        "spuStr": $("#spuText").val(),
                        "skuStr": $("#skuText").val()
                    },
                    "2":{
                        "spuStr": $("#spuText1").val(),
                        "skuStr": $("#skuText1").val()
                    }
                }
            }),
            success: function (data) {
                if(data.code==0){
                    $.Huimodalalert('提交成功！',1000);
                    document.body.scrollTop = document.documentElement.scrollTop = 0;
                    setTimeout(function(){
                        location.reload();
                    },1000);
                }
                else if(data.code==1){
                    $("#bottm").attr("disabled", false);
                    layer.confirm(data.message, function(index){

                        layer.close(index);
                    });
                    // $.Huimodalalert(data.message,2000);
                }

            },
            error:function () {
                $.Huimodalalert('创建失败,请重新提交！',2000);
            }
        });
    }})

/*function check(){
    console.log(firstLevel);
    console.log(secondLevel);
    console.log(thirdLevel);

    console.log("range="+range);

    console.log("firstlength="+firstlength);
    console.log("firstLevel.length="+firstLevel.length);

}*/
/*function goods_listCategory4(classNum, parentId,grandParentId) {
    console.log(grandParentId)
    $("#classDiv4").css({
        display: "block"
    });
    $(".removeEl4").remove();
    var user_data = {
        // category_level: classNum,
        category_id: parentId
    }
    var succCallBack = function (data, status, response) {
        if (data.errorCode == "0") {
            if (data.data.length == 0) {
                $("#classSet4").append('<li class="removeEl4 clearfix pl-10 mb-5">无数据</li>');
            } else {
                for (var i = 0; i < data.data.length; i++) {
                    $("#classSet4").append('<li class="removeEl4 clearfix pl-10 mb-5"><div class="f-l pd-5" onclick="nextbox4(this,'+data.data[i].category_code+')"><input name="classification04" type="radio" value="' + data.data[i].category_id + '" class="checkbox" /><label class="pl-10">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                }
            }
        }
    };
    return web.doAjax(root.goodsInter.goods_subCategory, 'post', user_data, succCallBack);
}*/
